import json
import time
import hashlib
import random
from WebFrame.ORM import select,insert,Dict2Obj,update,delete

SESSION_KEY=['id','key','value','creat_time','last_time']


    

def hash(content: str) -> str:

    content = content.encode('utf-8')
    md5hash = hashlib.md5(content)
    md5 = md5hash.hexdigest()
    return md5


def getRandom(randomlength=16):

    digits = '0123456789'
    ascii_letters = 'abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    str_list = [random.choice(digits + ascii_letters)
                for i in range(randomlength)]
    random_str = ''.join(str_list)
    return random_str

class Session(object):
    # id=None
    # key=None#mde5 散列cookie得到
    # value={}#存值
    # creat_time=None#创建时间
    # last_time=None#最后使用时间
    
    def __init__(self,key=None,effective_time=10,) -> None:
        self.key=key
        self.effective_time=effective_time #有效时间 用于刷新session
        self.set_session()
    def set_session(self):
        now =  time.localtime()
        now_time=time.strftime("%Y-%m-%d %H:%M:%S", now)
        if not self.get():
            value="{}"
            sql=f"INSERT INTO `session` (`key`, `value`, `creat_time`, `last_time`) VALUES ('{self.key}', '{value}', '{now_time}', '{now_time}')"
            insert(sql)
    def update(self,data={}):#更新
        
        now_data=self.get()
        now_data.update({'token':hash(getRandom())})
        now_data.update(data)
        now_data=json.dumps(now_data)
        now =  time.localtime()
        now_time=time.strftime("%Y-%m-%d %H:%M:%S", now)
        sql2=f"UPDATE `session` SET`value`='{now_data}', `last_time`='{now_time}' WHERE (`key`='{self.key}')"
        
        
        update(sql2,())
    def get(self):#获取
        """
        获取当前session
        更新最后时间
        """
        sql=f"SELECT * from session where `key`='{self.key}'"
        now_session=select(sql,(),SESSION_KEY)
        if now_session:
            now_data=now_session[0].value
        
            return json.loads(now_data)
        else:
            return {}


